package com.leyou.sms.listeners;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class SmsListeners {


    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "sms.queue", durable = "true"),
                    exchange = @Exchange(value = "sms",type = ExchangeTypes.TOPIC),
                    key = "sms.verify"
            )
    )
    public void sendSms(Map<String, String> msg) {

        String phone = msg.get("phone");

        if (StringUtils.isEmpty(phone)|| !RegexUtils.isPhone(phone)){
            throw new LyException(400,"手机号有误");
        }

        String code = msg.get("code");

        //TODO 判断，code是否包含字母（52），数字（10），之外的内容

        if (StringUtils.isEmpty(code)){
            throw new LyException(400,"发送内容不能为空");
        }


        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5tMqMBJu6xa16U382YhF", "IdHXp7tUxSx5ImhbOE9guz12eOFCkF");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "乐优商城");
        request.putQueryParameter("TemplateCode", "SMS_143719983");
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info("短信发送成功");
            log.info(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }

    }
}
